<template>
  <div class="setting-content position-container">
    <h2 class="setting-header">
      <strong>职位管理</strong>
    </h2>
    <!-- 顶部操作栏 -->
    <div class="setting-operation position-operation">
      <div class="setting-operation-left">
        <el-button v-permission="['recruitment:admin:position:add']" type="primary" @click="showPublishDialog">发布职位</el-button>
        <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="searchForm" @onSubmit="handleSearch" />
      </div>
      <div class="setting-operation-right">
        <div class="change-card">
          <el-tooltip content="列表模式" placement="bottom" effect="light">
            <a :class="{ active: !showCard }" href="javascript:;" @click="showCard = false"><i class="iconfont">&#xe6ca;</i></a>
          </el-tooltip>
          <el-tooltip content="卡片模式" placement="bottom" effect="light">
            <a :class="{ active: showCard }" href="javascript:;" @click="showCard = true"><i class="iconfont">&#xe6c9;</i></a>
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 职位列表 -->
    <div v-if="showCard" class="position-list">
      <el-row v-if="tableData.length" :gutter="20">
        <el-col :span="8" v-for="position in tableData" :key="position.id">
          <el-card class="position-card" shadow="hover" @click="showDetail(position)">
            <template #header>
              <div class="card-header">
                <div class="checkbox-wrapper" @click.stop>
                  <el-checkbox 
                    v-model="position.checked" 
                    :class="{ 'visible': position.checked }"
                    @change="handleCheckTable(position.id)"
                  />
                </div>
                <el-popover title="职位描述" placement="right" :content="position.description || '暂无描述'" :width="400" trigger="hover">
                  <template #reference>
                    <h3>{{ position.name }}</h3>
                  </template>
                </el-popover>
                <div class="header-info">
                  <span class="period">{{ dayjs(position.startTime).format('YYYY-MM-DD') }} - {{ dayjs(position.deadline).format('YYYY-MM-DD') }}</span>
                  <el-tag size="small" :type="STATE_MAP[position.state]?.type">
                    {{ STATE_MAP[position.state]?.label || '未知状态' }}
                  </el-tag>
                </div>
              </div>
            </template>

            <template #default>
              <div class="position-info">
                <!-- 第一行：基本要求 + 招聘人数 -->
                <div class="requirements">
                  <div class="requirement-group">
                    <div class="requirement-item">
                      <el-icon><School /></el-icon>
                      {{ DEGREE_MAP[position.degree]?.label || '学历不限' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                      <el-icon><Timer /></el-icon>
                      {{ EXPERIENCE_MAP[position.workExperience]?.label || '经验不限' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                      <el-icon><Collection /></el-icon>
                      {{ position.major || '专业不限' }}
                    </div>
                  </div>
                  <div class="count-info">招聘 {{ position.num || 1 }} 人</div>
                </div>

                <!-- 第二行：工作地点 + 年龄 + 简历数量 -->
                <div class="requirements">
                  <div class="requirement-group">
                    <div class="requirement-item">
                      <el-icon><Location /></el-icon>
                      {{ position.address || '地点未设置' }}
                    </div>
                    <el-divider direction="vertical" />
                    <div class="requirement-item">
                      <el-icon><User /></el-icon>
                      {{ position.age || '年龄不限' }}
                    </div>
                  </div>
                  <div class="count-info" @click.stop="showStatistics(position)">查看简历({{ position.applicantsNum || 0 }}份)</div>
                </div>

                <!-- 第三行：操作按钮 -->
                <div class="actions">
                  <el-button v-permission="['recruitment:admin:position:delete']" link type="primary" @click.stop="handleDelete(position)">删除</el-button>
                  <el-dropdown v-if="position.state === 1" placement="bottom" style="margin: 0 12px">
                    <el-button v-if="hasPermission(['recruitment:admin:position:edit'])" link type="primary" @click.stop>审核</el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click.stop="handleAudit(position, 2)">通过</el-dropdown-item>
                        <el-dropdown-item @click.stop="handleAudit(position, 4)">通过并开启</el-dropdown-item>
                        <el-dropdown-item @click.stop="handleAudit(position, 3)">不通过</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                  <el-button link type="primary" @click.stop="handleUpdateState(position, 4)" v-if="hasPermission(['recruitment:admin:position:edit']) && [2, 5].includes(position.state)">开启</el-button>
                  <el-button link type="primary" @click.stop="handleUpdateState(position, 5)" v-if="hasPermission(['recruitment:admin:position:edit']) && position.state === 4">关闭</el-button>
                  <el-button link type="primary" @click.stop="handleEdit(position)" v-if="hasPermission(['recruitment:admin:position:edit'])">编辑</el-button>
                </div>
              </div>
            </template>
          </el-card>
        </el-col>
      </el-row>
      <el-empty v-else description="暂无数据" />
    </div>
    <div v-else class="position-list">
      <RuifoxTable v-loading="tableLoading" v-model:tableData="tableData" :field-list="fieldList" :default-checkbox="true" :default-index="true">
        <!-- 多选 -->
        <template #default-checkbox="{ element }">
          <div class="table-div-check">
            <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size="" />
          </div>
        </template>
        <!-- 招聘时间 -->
        <template #range="{ element }">{{ dayjs(element.startTime).format('YYYY-MM-DD') }} - {{ dayjs(element.deadline).format('YYYY-MM-DD') }}</template>
        <!-- 状态 -->
        <template #state="{ element }">
          <el-tag :type="STATE_MAP[element.state]?.type">
            {{ STATE_MAP[element.state]?.label || '未知状态' }}
          </el-tag>
        </template>
        <template #isOpen="{ element }">
          <el-switch
            v-model="element.state"
            :active-value="4"
            :inactive-value="5"
            :before-change="() => handleBeforeChange(element)"
          />
        </template>
        <!-- 操作 -->
        <template #options="{ element }">
          <div class="table-td-option">
            <el-button link type="primary" @click="showStatistics(element)">查看简历</el-button>
            <el-button link type="primary" :disabled="!(element.state === 1 && hasPermission(['recruitment:admin:position:edit']))" @click="showAudit(element)">审核</el-button>
            <el-dropdown>
              <span class="el-dropdown-link">
                <i class="iconfont">&#xe78d;</i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="showDetail(element)">详情</el-dropdown-item>
                  <el-dropdown-item @click="handleEdit(element)" v-if="hasPermission(['recruitment:admin:position:edit'])">编辑</el-dropdown-item>
                  <!-- <el-dropdown-item @click="handleUpdateState(element, 4)" v-if="hasPermission(['recruitment:admin:position:edit']) && [2, 5].includes(element.state)">开启</el-dropdown-item>
                  <el-dropdown-item @click="handleUpdateState(element, 5)" v-if="hasPermission(['recruitment:admin:position:edit']) && element.state === 4">关闭</el-dropdown-item> -->
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </RuifoxTable>
    </div>
    <PaginationView
      :total="queryData.total"
      :pageSize="queryData.pageSize"
      :currentPage="queryData.currentPage"
      :allChoose="isAllChooseBtn"
      :pageChoose="isPageChooseBtn"
      :options="batchOptions"
      :checkedNum="checkedNum"
      :canChoose="queryData.total > 0"
      @changeSize="handleSizeChange"
      @currentChange="handleCurrentChange"
      @changePageChoose="handlePageChoose"
      @changeAllChoose="handleAllChoose"
      @invertChoose="handleInvertChoose"
      @checkOption="handleBatchOption"
      @refreshList="getTableData"
      @cancelChoose="handleResetPagination"
    />

    <!-- 发布/编辑职位对话框 -->
    <el-drawer v-model="dialogVisible" :title="positionForm.id ? '编辑职位' : '发布新职位'">
      <el-scrollbar>
        <el-form ref="positionFormRef" :model="positionForm" :rules="rules" label-width="auto" label-position="right" class="position-form">
          <h2>1.职位基本信息</h2>
          <el-form-item label="职位名称" prop="name">
            <el-input v-model="positionForm.name" placeholder="请输入职位名称" maxlength="120" show-word-limit />
          </el-form-item>
          <el-form-item label="职位描述" prop="description">
            <el-input v-model="positionForm.description" type="textarea" :rows="6" placeholder="请输入职位描述" />
          </el-form-item>
          <el-form-item label="工作地点" prop="address">
            <el-input v-model="positionForm.address" placeholder="请输入工作地点" />
          </el-form-item>
          <el-form-item label="招聘人数" prop="num">
            <el-input-number v-model="positionForm.num" :min="1" :max="999" />
          </el-form-item>

          <el-form-item label="申请表单" props="paperId">
            <el-select v-model="positionForm.paperId" placeholder="请选择申请表单">
              <el-option v-for="item in paperList" :key="item.id" :label="item.title" :value="item.id" />
            </el-select>
            <el-button type="primary" plain @click="handleCreatePaper" style="margin-left: 10px">去创建</el-button>
          </el-form-item>

          <el-form-item label="标签">
            <el-tag v-for="tag in positionForm.customizationList" :key="tag" closable class="mx-1" @close="handleTagClose(tag)">
              {{ tag }}
            </el-tag>
            <el-input v-if="inputVisible" ref="tagInputRef" v-model="inputValue" class="w-100" size="small" @keyup.enter="handleTagInputConfirm" @blur="handleTagInputConfirm" />
            <el-button v-else size="small" @click="showTagInput">+ 新标签</el-button>
          </el-form-item>
          <h2>2.职位要求</h2>
          <el-form-item label="工作经验" prop="workExperience">
            <el-select v-model="positionForm.workExperience" placeholder="请选择工作经验要求">
              <el-option v-for="item in EXPERIENCE_MAP" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="学历要求" prop="degree">
            <el-select v-model="positionForm.degree" placeholder="请选择学历要求">
              <el-option v-for="item in DEGREE_MAP" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="专业要求" prop="major">
            <el-input v-model="positionForm.major" placeholder="请输入专业要求" />
          </el-form-item>
          <SalaryRangeInput v-model:salaryLeft="positionForm.salaryLeft" v-model:salaryRight="positionForm.salaryRight" v-model:salaryType="positionForm.salaryType" />
          <el-form-item label="年龄要求" prop="age">
            <el-input v-model="positionForm.age" placeholder="请输入年龄要求" />
          </el-form-item>
          <el-form-item label="性别要求" prop="gender">
            <el-select v-model="positionForm.gender" placeholder="请选择性别要求">
              <el-option v-for="item in GENDER_MAP" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="招聘时间" required>
            <el-date-picker v-model="positionForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="x" />
          </el-form-item>
        </el-form>

      </el-scrollbar>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-drawer>

    <!-- 简历统计 -->
    <el-drawer v-model="statisticsVisible" :title="`${currentPosition?.name || ''} 统计数据`" direction="rtl" size="50%">
      <Statistics v-if="statisticsVisible" :position="currentPosition" />
    </el-drawer>

    <!-- 详情 -->
    <el-drawer v-model="detailVisible" :title="`${currentPosition?.name} 详情`" direction="rtl" size="500px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="职位名称" min-width="80px">{{ currentPosition.name }}</el-descriptions-item>
        <el-descriptions-item label="招聘人数">{{ currentPosition.num }}人</el-descriptions-item>
        <el-descriptions-item label="专业要求">{{ currentPosition.major }}</el-descriptions-item>
        <el-descriptions-item label="学历要求">
          {{ DEGREE_MAP[currentPosition.degree]?.label }}
        </el-descriptions-item>
        <el-descriptions-item label="性别要求">
          {{ GENDER_MAP[currentPosition.gender]?.label }}
        </el-descriptions-item>
        <el-descriptions-item label="工作经验">
          {{ EXPERIENCE_MAP[currentPosition.workExperience]?.label }}
        </el-descriptions-item>
        <el-descriptions-item label="年龄要求">{{ currentPosition.age }}</el-descriptions-item>
        <el-descriptions-item label="工作地点">{{ currentPosition.location }}</el-descriptions-item>
        <el-descriptions-item label="招聘时间">{{ dayjs(currentPosition.startTime).format('YYYY-MM-DD') }} - {{ dayjs(currentPosition.deadline).format('YYYY-MM-DD') }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="STATE_MAP[currentPosition.state].type">
            {{ STATE_MAP[currentPosition.state].label }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="标签">
          <el-tag v-for="tag in currentPosition.customizationList" :key="tag" class="mx-1">
            {{ tag }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="职位描述">
          <div style="white-space: pre-line">{{ currentPosition.description }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="申请表单">
          {{ paperList.find(item => item.id === currentPosition.paperId)?.title || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="已收简历">{{ currentPosition.applicantsNum || 0 }}份</el-descriptions-item>
      </el-descriptions>
    </el-drawer>
    <!-- 审核 -->
    <el-dialog
      v-model="auditVisible"
      title="审核职位"
      width="600px"
      :before-close="handleClose"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="职位名称" min-width="80px">{{ currentPosition.name }}</el-descriptions-item>
        <el-descriptions-item label="招聘人数">{{ currentPosition.num }}人</el-descriptions-item>
        <el-descriptions-item label="专业要求">{{ currentPosition.major }}</el-descriptions-item>
        <el-descriptions-item label="学历要求">
          {{ DEGREE_MAP[currentPosition.degree]?.label }}
        </el-descriptions-item>
        <el-descriptions-item label="性别要求">
          {{ GENDER_MAP[currentPosition.gender]?.label }}
        </el-descriptions-item>
        <el-descriptions-item label="工作经验">
          {{ EXPERIENCE_MAP[currentPosition.workExperience]?.label }}
        </el-descriptions-item>
        <el-descriptions-item label="年龄要求">{{ currentPosition.age }}</el-descriptions-item>
        <el-descriptions-item label="工作地点">{{ currentPosition.location }}</el-descriptions-item>
        <el-descriptions-item label="招聘时间">{{ dayjs(currentPosition.startTime).format('YYYY-MM-DD') }} - {{ dayjs(currentPosition.deadline).format('YYYY-MM-DD') }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="STATE_MAP[currentPosition.state].type">
            {{ STATE_MAP[currentPosition.state].label }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="标签">
          <el-tag v-for="tag in currentPosition.customizationList" :key="tag" class="mx-1">
            {{ tag }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="职位描述">
          <div style="white-space: pre-line">{{ currentPosition.description }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="申请表单">
          {{ paperList.find(item => item.id === currentPosition.paperId)?.title || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="已收简历">{{ currentPosition.applicantsNum || 0 }}份</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleAudit(currentPosition, 3)">不通过</el-button>
          <el-button type="primary" @click="handleAudit(currentPosition, 2)">
            通过
          </el-button>
          <el-button type="primary" @click="handleAudit(currentPosition, 4)">
            通过并开启
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { School, Collection, Timer, User, Location } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { selectRecPage, insertPost, updatePost, updateState, updateStatesList, deletePost, deletePostList, selectFormList, auditPost } from '@/api/position'
import { encrypt, jumpRoute, tableList as mixTable, hasPermission } from '@ruifox-cms/utils'

import dayjs from 'dayjs'
import Statistics from './components/Statistics'
import SalaryRangeInput from './components/SalaryRangeInput'

const {
  tableLoading,
  checkedList,
  isAllChooseBtn,
  isPageChooseBtn,
  isAllSearch,
  checkedNum,
  queryData,
  tableData,
  getTableData,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination
} = mixTable({
  getListApi: selectRecPage
})
const showCard = ref(false)
// 修改常量定义
const DEGREE_MAP = {
  0: { label: '不限', value: '0' },
  1: { label: '初中及以下', value: '1' },
  2: { label: '中专/中技', value: '2' },
  3: { label: '高中', value: '3' },
  4: { label: '大专', value: '4' },
  5: { label: '本科', value: '5' },
  6: { label: '硕士', value: '6' },
  7: { label: '博士', value: '7' }
}

const EXPERIENCE_MAP = {
  0: { label: '不限', value: '0' },
  1: { label: '应届生', value: '1' },
  2: { label: '1-3年', value: '2' },
  3: { label: '3-5年', value: '3' },
  4: { label: '5年以上', value: '4' }
}

const GENDER_MAP = {
  0: { label: '不限', value: '0' },
  1: { label: '男', value: '1' },
  2: { label: '女', value: '2' }
}

const STATE_MAP = {
  0: { label: '全部', type: 'info', value: 0 },
  1: { label: '待审核', type: 'info', value: 1 },
  2: { label: '审核通过', type: 'success', value: 2 },
  3: { label: '不通过', type: 'danger', value: 3 },
  4: { label: '进行中', type: 'success', value: 4 },
  5: { label: '已结束', type: 'info', value: 5 }
}

// 申请表单列表
const paperList = ref([])
const getPaperList = async () => {
  const params = {
    status: 2,
    qsType: 3,
    sort: 0
  }
  const res = await selectFormList(params)
  paperList.value = res.data
}
getPaperList()

// 创建申请表单
const handleCreatePaper = () => {
  const query = {
    id: encrypt(3),
    qsTypeName: encrypt('问卷类')
  }
  jumpRoute('/form/manage/design', query, '_blank')
}

// 修改搜索条件配置
const searchCmpArray = ref([
  { label: '职位名称', key: 'name' },
  { label: '截止时间', key: 'dateRange', form_type: 'datetime' },
  { label: '最低学历', key: 'degree', form_type: 'select', options: Object.values(DEGREE_MAP) },
  { label: '状态', key: 'state', form_type: 'select', options: Object.values(STATE_MAP) }
])

const fieldList = ref([
  { title: '职位名称', name: 'name' },
  { title: '招聘时间', name: 'range' },
  { title: '招聘人数', name: 'num' },
  { title: '已收到简历', name: 'applicantsNum' },
  { title: '状态', name: 'state' },
  { title: '是否开启', name: 'isOpen'},
  { title: '操作', name: 'options' }
])

// 搜索
queryData.state = 0
queryData.pageSize = 9
const searchForm = ref({state: 0})
const handleSearch = () => {
  Object.assign(queryData, searchForm.value)
  if (searchForm.value.dateRange?.length) {
    queryData.timeStartDeadline = dayjs(searchForm.value.dateRange[0]).valueOf() / 1000
    queryData.timeEndDeadline = dayjs(searchForm.value.dateRange[1]).valueOf() / 1000
    delete queryData.dateRange
  } else {
    delete queryData.timeStartDeadline
    delete queryData.timeEndDeadline
  }
  getTableData()
}


// 表单数据
const rules = {
  name: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
  num: [{ required: true, message: '请输入招聘人数', trigger: 'blur' }],
  major: [{ required: true, message: '请输入专业要求', trigger: 'blur' }],
  degree: [{ required: true, message: '请选择学历要求', trigger: 'change' }],
  address: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
  workExperience: [{ required: true, message: '请选择工作经验要求', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄要求', trigger: 'blur' }],
  description: [{ required: true, message: '请输入职位描述', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  deadline: [{ required: true, message: '请选择截止时间', trigger: 'change' }],
  paperId: [{ required: true, message: '请选择申请表单', trigger: 'change' }]
}
const defaultPositionForm = {
  name: '', // 职位名称
  num: 1, // 招聘人数
  major: '', // 专业要求
  degree: '', // 学历要求
  gender: '0', // 性别要求
  workExperience: '', // 工作经验
  age: '', // 年龄要求
  customizationList: [], // 自定义要求（标签数组）
  description: '', // 职位描述
  startTime: '', // 开始时间
  deadline: '', // 截止时间
  address: '', // 工作地点
  paperId: undefined, // 申请表单ID
  salaryLeft:0,
  salaryRight:0,
  salaryType: 'monthly'
}
const positionForm = ref({ ...defaultPositionForm })
const positionFormRef = ref(null)
const dialogVisible = ref(false)

// 添加职位
const showPublishDialog = () => {
  positionForm.value = { ...defaultPositionForm }
  dialogVisible.value = true
}

// 编辑职位
const handleEdit = position => {
  if (position.applicantsNum > 0) {
    ElMessage.warning('该职位已收到简历，无法编辑。请关闭后重新发布新职位！')
    return
  }
  ElMessageBox.confirm('是否编辑所选职位？编辑后将重新进入审核状态。', '编辑确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    positionForm.value = { ...position }
    positionForm.value.dateRange = [position.startTime, position.deadline]
    dialogVisible.value = true
  })
}

// 关闭标签
const handleTagClose = tag => {
  positionForm.value.customizationList = positionForm.value.customizationList.filter(t => t !== tag)
}

// 显示标签输入框
const inputVisible = ref(false)
const inputValue = ref('')
const tagInputRef = ref(null)
const showTagInput = () => {
  inputVisible.value = true
  nextTick(() => {
    tagInputRef.value.focus()
  })
}

// 确认标签输入
const handleTagInputConfirm = () => {
  if (inputValue.value && !positionForm.value.customizationList.includes(inputValue.value)) {
    if (!positionForm.value) {
      positionForm.value = []
    }
    positionForm.value.customizationList.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 提交表单
const handleSubmit = async () => {
  if (!positionFormRef.value) return

  await positionFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        positionForm.value.startTime = positionForm.value.dateRange[0]
        positionForm.value.deadline = positionForm.value.dateRange[1]
        delete positionForm.value.dateRange
        const res = await (positionForm.value.id ? updatePost(positionForm.value) : insertPost(positionForm.value))
        if (res.code === 20000) {
          ElMessage.success(positionForm.value.id ? '职位已更新' : '职位已发布')
          dialogVisible.value = false
          getTableData()
        }
      } catch (error) {
        console.error('保存职位失败:', error)
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 删除职位
const handleDelete = async data => {
  try {
    await ElMessageBox.confirm('是否删除所选职位？', '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deletePost({ id: data.id })
    if (res.code === 20000) {
      ElMessage.success('删除成功')
      getTableData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm('是否批量删除所选职位？', '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const data = { ids: checkedList.value, isAllChoose: isAllSearch.value }
    const res = await deletePostList(data)
    if (res.code === 20000) {
      ElMessage.success('批量删除成功')
      handleResetPagination()
      getTableData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

// 更新状态
const handleBeforeChange = (element) => {
  // 保存当前状态用于回滚
  const originalState = element.state;
  
  // 返回一个 Promise，在用户确认后执行状态更新
  return new Promise((resolve) => {
    ElMessageBox.confirm('是否更新所选职位状态？', '更新确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    .then(async () => {
      // 用户点击确认，执行状态更新
      try {
        const res = await updateState({
          id: element.id,
          state: element.state === 4 ? 5 : 4 // 切换状态
        });
        
        if (res.code === 20000) {
          ElMessage.success('状态更新成功');
          getTableData(); // 刷新表格数据
          resolve(true); // 允许切换
        } else {
          // 更新失败，回滚状态
          element.state = originalState;
          ElMessage.error('状态更新失败');
          resolve(false); // 阻止切换
        }
      } catch (error) {
        // 发生错误，回滚状态
        element.state = originalState;
        ElMessage.error('状态更新失败');
        resolve(false); // 阻止切换
      }
    })
    .catch(() => {
      // 用户点击取消，回滚状态
      element.state = originalState;
      resolve(false); // 阻止切换
    });
  });
}
// 批量更新状态
const handleBatchUpdateState = async state => {
  try {
    await ElMessageBox.confirm('是否更新所选职位状态？', '更新确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    
    const data = { ids: checkedList.value, isAllChoose: isAllSearch.value, state }
    const res = await updateStatesList(data)
    if (res.code === 20000) {
      ElMessage.success('批量更新状态成功')
      handleResetPagination()
      getTableData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量更新状态失败:', error)
    }
  }
}

// 审核职位
const auditVisible = ref(false)
const showAudit = position => {
  currentPosition.value = position
  auditVisible.value = true
}
const handleAudit = async (data, state) => {
  ElMessageBox.confirm('是否审核所选职位？', '审核确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    const res = await auditPost({id: data.id, state})
    if (res.code === 20000) {
      ElMessage.success('审核成功')
      getTableData()
    }
  })
}
// 批量操作
const batchOptions = [
  { name: '删除', value: 'delete' },
  { name: '关闭', value: 'offline' },
  { name: '开启', value: 'online' }
]
const handleBatchOption = val => {
  if (val === 'delete') {
    handleBatchDelete()
  } else if (val === 'offline') {
    handleBatchUpdateState(5)
  } else if (val === 'online') {
    handleBatchUpdateState(4)
  }
}

// 添加显示统计的方法
const statisticsVisible = ref(false)
const currentPosition = ref(null)
const showStatistics = position => {
  currentPosition.value = position
  statisticsVisible.value = true
}

// 添加详情相关变量和方法
const detailVisible = ref(false)

const showDetail = position => {
  currentPosition.value = position
  detailVisible.value = true
}

onMounted(() => {
  getTableData()
  window['updateFormDesignList'] = val => {
    ElMessage({
      showClose: true,
      message: val,
      type: 'success'
    })
    getPaperList()
  }
})
</script>

<style lang="scss" scoped>
.position-container {
  .setting-operation {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    .setting-operation-left {
      display: flex;
      gap: 10px;
      flex: 1;
    }
    .setting-operation-right {
      display: flex;
      gap: 10px;
      .change-card {
        height: 32px;
        width: 64px;
        box-sizing: border-box;
        border: var(--el-border);
        border-radius: 4px;
        display: flex;
        overflow: hidden;
        a {
          display: flex;
          width: 50%;
          height: 100%;
          align-items: center;
          justify-content: center;
        }
        a.active {
          background-color: $mainColor;
          i {
            color: #fff;
          }
        }
      }
    }
  }

  .position-card {
    margin-bottom: 20px;
    transition: all 0.3s;
    cursor: pointer;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    :deep(.el-card__header) {
      padding: 16px 20px;
      border-bottom: 1px solid #ebeef5;
      position: relative;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 10px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        max-width: 60%;
        @include textEllipsis(20px, 1);
      }

      .header-info {
        flex-shrink: 0;
        display: flex;
        align-items: center;
        gap: 12px;

        .period {
          color: #909399;
          font-size: 14px;
        }
      }

      .checkbox-wrapper {
        position: absolute;
        top: -9px;
        right: 0;
        z-index: 1;

        :deep(.el-checkbox) {
          opacity: 0;
          transition: opacity 0.3s;

          &.visible {
            opacity: 1;
          }
        }
      }
    }

    &:hover {
      .checkbox-wrapper {
        :deep(.el-checkbox) {
          opacity: 1;
        }
      }
    }

    .position-info {
      .requirements {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .requirement-group {
          display: flex;
          align-items: center;
          gap: 8px;

          .requirement-item {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            color: #606266;
            font-size: 12px;

            .el-icon {
              color: #909399;
            }
          }
        }
      }

      .count-info {
        color: $mainColor;
        font-size: 12px;
        display: flex;
        align-items: center;
        gap: 4px;
        white-space: nowrap;
        cursor: pointer;
      }

      .actions {
        padding-top: 12px;
        border-top: 1px solid #ebeef5;
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}
//表单分类
.position-form {
  h2 {
    font-size: 16px;
    margin-bottom: 20px;
  }
}
// 只保留表单中使用的辅助类
.mx-1 {
  margin: 2px 4px 0;
}

.w-100 {
  width: 100px;
}

// 添加描述列表样式
:deep(.el-descriptions) {
  .el-descriptions__body {
    .el-descriptions__table {
      .el-descriptions__cell {
        .el-tag {
          margin: 2px;
        }
      }
    }
  }
}
</style>
